package com.irdstudio.efp.esb.api.rest.sed.ploaninfo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.sequence.service.DefaultPatternDescriptor;
import com.irdstudio.basic.sequence.service.PatternDescriptor;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalRepayPlan;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalRepayPlan;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.service.sed.SedCommonService;
import com.irdstudio.efp.esb.api.service.sed.ploaninfo.PersonalRepayPlanService;
import com.irdstudio.efp.esb.common.constant.ESBClientConstance;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.bo.req.hj.ReqRepaymentDetailsInfoQueryBean;
import com.irdstudio.efp.esb.service.bo.resp.hj.AcctDtlInfBean;
import com.irdstudio.efp.esb.service.bo.resp.hj.RespRepaymentPlanListQueryBean;
import com.irdstudio.efp.esb.service.facade.hj.LoanInfoQueryService;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.facade.LoanRepayPlanService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.LoanRepayPlanVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.irdstudio.basic.sequence.service.DefaultPatternDescriptor.*;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】
 * 问题编号：【】
 * 服务场景描述：个人还款计划查询 <br>
 *
 * @author xiaojunhui
 * @version 0.1
 * @date 2019/5/20 17:30
 */
@RestController
@RequestMapping("/esb")
public class PersonalRepayPlanController implements FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(PersonalRepayPlanController.class);

    private final PatternDescriptor pattern =
            DefaultPatternDescriptor.of(ESBClientConstance.CnsmrSysNo +
                    YEAR_2 + MONTH + DAY + HOUR + MIN + SECOND + SEQ, 6);

    @Autowired
    private SedCommonService<RespPersonalRepayPlan> sedCommonService;

    @Autowired
    private PersonalRepayPlanService personalRepayPlanService;

    @Autowired
    @Qualifier("accLoanRepayPlanService")
    private LoanRepayPlanService loanRepayPlanService;

    @Autowired
    private AccLoanService accLoanService;

    @Autowired
    private LoanInfoQueryService loanInfoQueryService;

    @Autowired
    private PatternedLimitableSeqService patternedLimitableSeqService;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private NlsApplyInfoService nlsApplyInfoService;


    /**
     * 获取ESB请求对象，校验ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqPersonalRepayPlan")
    public ReqPersonalRepayPlan getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqPersonalRepayPlan.class, Feature.InternFieldNames);
    }

    /**
     * 处理请求
     *
     * @param esbReqServiceBean    esb请求对象
     * @param br1
     * @param reqPersonalRepayPlan 返回对象
     * @param br2
     * @param exception
     * @return
     */
    @PostMapping("/SERVICE_30230002_04")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqPersonalRepayPlan") ReqPersonalRepayPlan reqPersonalRepayPlan,
                                     BindingResult br2, Exception exception) {
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("还款计划查询开始,全局流水号为：[{}]", glblSrlNo);
        //响应体
        RespPersonalRepayPlan respPersonalRepayPlan = new RespPersonalRepayPlan();
        if (Objects.nonNull(exception)) {
            //如果异常不为空，那么处理异常返回信息
            return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, exception, respPersonalRepayPlan, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
        }
        //页码-当前查询第几页的数据
        String pageNo = reqPersonalRepayPlan.getPageNo();
        //每页显示条数
        String pageSize = reqPersonalRepayPlan.getPageSize();

        try {
            String openDay = pubSysInfoService.getOpenday("1001");
            if (StringUtils.isEmpty(openDay)) {
                throw new Exception("获取openday为空");
            }
            //LoanRepayPlanVO queryParam = personalRepayPlanService.transferQueryParams.transfer(reqPersonalRepayPlan);
            AccLoanVO loanPkParam = new AccLoanVO();
            loanPkParam.setBillNo(reqPersonalRepayPlan.getBillNo());
            AccLoanVO accLoanVO = accLoanService.queryByPk(loanPkParam);
            if (Objects.isNull(accLoanVO)) {
                return sedCommonService.getSucessBean(esbReqServiceBean, respPersonalRepayPlan, RespRetCode.SUCCESS);
                //return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, new Exception("根据借据号获取到的借据信息为空"), respPersonalRepayPlan, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
            }

            NlsApplyInfoVO pkParam = new NlsApplyInfoVO();
            pkParam.setApplySeq(accLoanVO.getApplySeq());
            NlsApplyInfoVO nlsApplyInfoVO = nlsApplyInfoService.queryByPk(pkParam);
            if (Objects.isNull(nlsApplyInfoVO)) {
                return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, new Exception("根据借据号获取到用信信息为空"), respPersonalRepayPlan, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG );
            }

            int[] offsetLimt = sedCommonService.getOffsetLimt(pageNo, pageSize);
            /**查询符合条件的数量
             int totalSize = loanRepayPlanService.queryCountByRefNbr(queryParam);
             List<LoanRepayPlanVO> loanRepayPlanVOS = new ArrayList<LoanRepayPlanVO>();
             if (offsetLimt[0] <= totalSize) {
             loanRepayPlanVOS = loanRepayPlanService.queryPageByRefNbr(queryParam, offsetLimt[0], offsetLimt[1]);
             }*/
            //根据贷款号发放号查询互金的还款计划
            //互金-还款计划查询
            ReqRepaymentDetailsInfoQueryBean reqRepaymentDetailsInfoQueryBean = new ReqRepaymentDetailsInfoQueryBean();
            reqRepaymentDetailsInfoQueryBean.setAcctNo(accLoanVO.getLoanSeq());
            reqRepaymentDetailsInfoQueryBean.setDistrNo(accLoanVO.getDistrNo());
            RespRepaymentPlanListQueryBean respRepaymentPlanListQueryBean = loanInfoQueryService.repaymentPlanListQuery(reqRepaymentDetailsInfoQueryBean, glblSrlNo);
            List<AcctDtlInfBean> acctDtlInfArry = respRepaymentPlanListQueryBean.getAcctDtlInfArry();
            //封装响应报文
            personalRepayPlanService.handleResp(respPersonalRepayPlan, accLoanVO, acctDtlInfArry, offsetLimt, acctDtlInfArry.size(), openDay);
            //返回报文
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respPersonalRepayPlan, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");
        } catch (BizException bizException) {
            logger.error("还款明细接口出现异常，异常信息为：", bizException.getMessage());
            bizException.printStackTrace();
            return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, bizException, respPersonalRepayPlan, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);

        } catch (Exception ex) {
            logger.error("还款明细接口出现异常，异常信息为：", ex.getMessage());
            ex.printStackTrace();
            return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, ex, respPersonalRepayPlan, RespRetCode.FAILE, EsbRetCodeStandard.SJCLYC);
        }
    }
}
